package jmine.tec.hydra.script.impl;

import java.util.Map;

import jmine.tec.hydra.script.RenderMessageScriptContext;
import jmine.tec.hydra.util.stream.InputableOutputStream;
import jmine.tec.script.ScriptLogger;
import jmine.tec.script.impl.ScriptLoggerImpl;
import jmine.tec.script.persistent.context.impl.AbstractScriptExecutionContext;

/**
 * Contexto de execução de um script de renderização de mensagem.
 * 
 * @author lundberg
 */
public class RenderMessageScriptContextImpl extends AbstractScriptExecutionContext<RenderResultImpl> implements
        RenderMessageScriptContext {

    private static final String STREAM = "_stream";

    private static final String LOG = "_log";
    
    private static final String PARAM_MAP = "_parameterMap";

    /**
     * Construtor
     */
    public RenderMessageScriptContextImpl() {
        // OK
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void beforeExecution() {
        super.beforeExecution();
        this.getParameters().putParameter(STREAM, new InputableOutputStream());
        this.getParameters().putParameter(LOG, new ScriptLoggerImpl(), ScriptLogger.class);
    }

    /**
     * {@inheritDoc}
     */
    public RenderResultImpl getResult() {
        RenderResultImpl result = new RenderResultImpl();
        result.setStream((InputableOutputStream) this.getParameters().getParameterValues().get(STREAM));
        result.setScriptLogger((ScriptLogger) this.getParameters().getParameterValues().get(LOG));
        return result;
    }

    /**
     * {@inheritDoc}
     */
    public String getTracer() {
        ScriptLogger scriptLogger = (ScriptLogger) this.getParameters().getParameterValues().get(LOG);
        if (scriptLogger != null) {
            return scriptLogger.getTraces();
        }
        return null;
    }

    /**
     * Passa os parâmetros de renderização para o contexto de execução.
     * 
     * @param parameters parameters
     */
    public void setRenderParameters(Map<String, Object> parameters) {
        for (Map.Entry<String, Object> e : parameters.entrySet()) {
            this.getParameters().putParameter(e.getKey(), e.getValue());
        }
        this.getParameters().putParameter(PARAM_MAP, parameters);
    }

    /**
     * {@inheritDoc}
     */
    public RenderMessageScriptContext prepare(Map<String, Object> parameters) {
        this.setRenderParameters(parameters);
        return this;
    }
}
